package com.zlp.oauth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.LinkedList;
import java.util.List;


/** 
 * 认证服务器
 * @author LiPing.Zou
 * @date: 2021/3/15 14:22
 */
@Configuration
@EnableAuthorizationServer
@Slf4j(topic = "AuthorizationServerConfig")
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private UserDetailsService userDetailsService;

    @Resource(name = "jwtTokenStore")
    private TokenStore tokenStore;

    @Resource
    private TokenEnhancer tokenEnhancer;

    @Resource
    private DataSource dataSource;

    @Resource(name = "jwtTokenConverter")
    private JwtAccessTokenConverter jwtAccessTokenConverter;




    /**
     * 认证服务端点配置
     *
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

        // token 增强链
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new LinkedList<>();
        delegates.add(tokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        tokenEnhancerChain.setTokenEnhancers(delegates);

        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenStore(tokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(tokenEnhancerChain)
//                .reuseRefreshTokens(false)
        ;
    }

    /*@Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");
    }*/


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.withClientDetails(clientDetailsService(dataSource) );
//        clients.inMemory()
//                //客户端ID
//                .withClient("admin")
//                //秘钥
//                .secret(passwordEncoder.encode("admin"))
//                //重定向地址
//                .redirectUris("http://www.baidu.com")
//                //授权范围
//                .scopes("all")
//                /*
//                 * 授权类型
//                 * authorization_code：授权码模式
//                 * password:密码模式
//                 * sms: 短信模式
//                 * refresh_token: 刷新
//                 */
//                .authorizedGrantTypes("authorization_code", "password","sms","refresh_token");
    }


    /**
     * ClientDetailsService和AuthorizationCodeServices从数据库读取数据。
     * 将客户端信息存储到数据库
     * @param dataSource 数据源
     * @date: 2021/3/30 17:42
     * @return: org.springframework.security.oauth2.provider.ClientDetailsService 
     */
    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource) {

        log.info("clientDetailsService query client details ==>");
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        ((JdbcClientDetailsService) clientDetailsService).setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }



}
